<template>
  <uv-picker ref="picker" :columns="addressList" :showToolbar="false" round="10" :loading="loading" keyName="name"
    @change="change" @confirm="confirm">
    <template v-slot:head>
      <slot name="head" />
    </template>
  </uv-picker>
</template>
<script>
  import addressList from '@/utils/regions.json'

  export default {
    data() {
      return {
        loading: true,
        provinces: [], //省
        citys: [], //市
        areas: [], //区
        pickerValue: [0, 0, 0],
        defaultValue: [3442, 1, 2]
      }
    },
    created() {
      this.getData();
    },
    computed: {
      addressList() {
        return [this.provinces, this.citys, this.areas];
      }
    },
    methods: {
      getData() {
        this.provinces = addressList.sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1));
        setTimeout(() => {
          this.handlePickValueDefault()
          this.loading = false
        }, 200)
      },
      handlePickValueDefault() {
        // 设置省
        this.pickerValue[0] = this.provinces.findIndex(item => Number(item.id) === this.defaultValue[0]);
        // 设置市
        this.citys = this.provinces[this.pickerValue[0]]?.children || [];
        this.pickerValue[1] = this.citys.findIndex(item => Number(item.id) === this.defaultValue[1]);
        // 设置区
        this.areas = this.citys[this.pickerValue[1]]?.children || [];
        this.pickerValue[2] = this.areas.findIndex(item => Number(item.id) === this.defaultValue[2]);
        // 重置下位置
        this.$refs.picker.setIndexs([this.pickerValue[0], this.pickerValue[1], this.pickerValue[2]], true);
      },
      change(e) {
        if (this.loading) return;
        const {
          columnIndex,
          index,
          indexs
        } = e
        // 改变了省
        if (columnIndex === 0) {
          this.citys = this.provinces[index]?.children || []
          this.areas = this.citys[0]?.children || []
          this.$refs.picker.setIndexs([index, 0, 0], true)
        } else if (columnIndex === 1) {
          this.areas = this.citys[index]?.children || []
          this.$refs.picker.setIndexs(indexs, true)
        }
      },
      open(indexs) {
        this.$refs.picker.open();
        if (indexs) {
          this.$refs.picker.setIndexs([indexs[0], indexs[1], indexs[2]], true);
        } else {
          this.handlePickValueDefault()
        }
      },
      confirm(e) {
        this.$emit('confirm', e)
      }
    }
  }
</script>